import 'dart:io';
import 'package:zootix/apis/zt-api.dart' as Api;
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:zootix/store/zt_auth.store.dart';
import 'package:zootix/util/zt_media_util.dart';
import 'package:zootix/util/zt_photo_picker_util.dart';
import 'package:zootix/util/zt_loading_util.dart';
import 'package:zootix/util/zt_screen_adaper_util.dart';
import 'package:zootix/util/zt_snack_bar.util.dart';
import 'package:zootix/zt_app_theme.dart';

import '../util/zt_util.dart';

class ZtMyAvatarWidget extends StatelessWidget {
  final _controller = Get.put<ZtMyAvatarController>(ZtMyAvatarController());
  ZtMyAvatarWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Obx(() => Container(
              decoration: BoxDecoration(
                  image:
                      DecorationImage(fit: BoxFit.cover, image: _buildImage()),
                  border: Border.all(
                      color: ZtAppTheme.white, width: ZtScreenAdaper.sp(2)),
                  borderRadius: BorderRadius.circular(50)),
              height: ZtScreenAdaper.width(90),
              width: ZtScreenAdaper.width(90),
              child: const SizedBox(),
            )),
        Positioned(
            bottom: 0,
            right: 0,
            child: InkWell(
                onTap: () {
                  _controller.photoPicker();
                },
                child: Image(
                  height: ZtScreenAdaper.width(40),
                  image: const AssetImage('assets/images/photo_icon.png'),
                )))
      ],
    );
  }

  dynamic _buildImage() {
    return _controller.uploadImgFilePath.value.isNotEmpty
        ? FileImage(File(_controller.uploadImgFilePath.value))
        : NetworkImage(
            ZtAuthStore.to.userInfo.value.avatarThumbUrl ?? '',
          );
  }
  // Widget getShowImg() {
  //   // 1.选择的内存照片
  //   if (uploadImg != null) {
  //     return Image(fit: BoxFit.cover, image: FileImage(uploadImg!));
  //   }
  //   // 2.显示回显的照片url地址
  //   if (createDto['content'] != null) {
  //     return FadeInCacheImage(
  //       url: createDto['content'],
  //       height: 100,
  //       width: 100,
  //     );
  //   }

  //   // 3.添加图
  //   return Image(
  //       height: 100,
  //       width: 100,
  //       fit: BoxFit.cover,
  //       image: AssetImage('assets/images/common/icon_camera.png'));
  // }
}

class ZtMyAvatarController extends GetxController {
  final uploadImgFilePath = ''.obs;
  Future<void> photoPicker() async {
    ZtLogManger().putLog(
      ZtLogType.clickEvent,
      ZtLogManger.buildEvent(
          logType: ZtLogType.clickEvent, page: ZtLogPages.editavatar),
    );

    await ZtPhotoPickerUtil().showPicker(callback: (XFile pickedFile) async {
      await ZtLoadingUtil.show(status: 'Uploading...');
      try {
        String? filename = await ZtMediaUtil().uploadImg(File(pickedFile.path));
        if (filename.isNotEmpty) {
          final res = await Api.updateAvatar(filename);
          if (res.data != null) {
            ZtSnackBarUtil().success('Update avatar successfully');
          }
        }
        uploadImgFilePath(pickedFile.path);
        Get.back();
      } catch (e) {
        ZtSnackBarUtil().error('Update avatar failed.');
      } finally {
        await EasyLoading.dismiss();
      }
    });
  }
}
